<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\admin\common;

use App\Model\Admin\Admin;
use App\Model\Admin\AdminRole;
use App\Model\Admin\Dept;
use App\Model\Admin\Role;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;

class Auth
{
    #[Inject]
   protected SessionInterface $session;


    /**
     * 获取权限范围内的所有角色id.
     */
    public function getScopeRoleIds(bool $with_self = false): array
    {
        if (!$admin = admin()) {
            return [];
        }
        $role_ids = $admin['roles'];
        $rules = Role::whereIn('id', $role_ids)->pluck('rules')->toArray();
        if ($rules && in_array('*', $rules)) {
            return Role::pluck('id')->toArray();
        }
        $roles = Role::get();
        $tree = new Tree($roles);
        $descendants = $tree->getDescendant($role_ids, $with_self);
        return array_column($descendants, 'id');
    }

    /**
     * 获取部门范围内的所有子部门.
     */
    public function getScopeDeptIds(bool $with_self = false): array
    {
        if (! $admin = admin()) {
            return [];
        }
        $dept_id = $admin['dept_id'];
        $dept = Dept::query()->get();
        $tree = new Tree($dept);
        $descendants = $tree->getDescendant([$dept_id], $with_self);
        return array_column($descendants, 'id');
    }

    /**
     * 获取部门下的所有用户id.
     */
    public function getScopeDeptAdminIds(bool $with_self = false): array
    {
        $dept_all_ids = $this->getScopeDeptIds();
        if (empty($dept_all_ids)) {
            return [];
        }
        $admin_ids = Admin::whereIn('dept_id', $dept_all_ids)->pluck('id')->toArray();
        if ($with_self) {
            $admin_ids[] = admin_id();
        }
        return array_unique($admin_ids);
    }

    /**
     * 获取权限范围内的所有管理员id.
     */
    public function getScopeAdminIds(bool $with_self = false): array
    {
        $role_ids = $this->getScopeRoleIds();
        $admin_ids = AdminRole::whereIn('role_id', $role_ids)->pluck('admin_id')->toArray();
        if ($with_self) {
            $admin_ids[] = static::admin_id();
        }
        return array_unique($admin_ids);
    }

    /**
     * 兼容旧版本.
     * @deprecated
     */
    public function isSupperAdmin(int $admin_id = 0): bool
    {
        return $this->isSuperAdmin($admin_id);
    }

    /**
     * 是否是超级管理员.
     */
    public function isSuperAdmin(int $admin_id = 0): bool
    {
        if (! $admin_id) {
            if (! $roles = admin('roles')) {
                return false;
            }
        } else {
            $roles = AdminRole::where('admin_id', $admin_id)->pluck('role_id');
        }
        $rules = Role::whereIn('id', $roles)->pluck('rules');
        return $rules && in_array('*', $rules->toArray());
    }
}
